package cn.ccbom.bom.interview.controller;

import cn.ccbom.bom.interview.facade.dto.FileUploadDTO;
import cn.ccbom.bom.interview.facade.vo.FileDownloadVO;
import cn.ccbom.bom.interview.facade.vo.FileUploadVO;
import cn.ccbom.bom.interview.service.FileService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

/**
 * 附件
 *
 * @author bom
 */
@Controller
@RequestMapping("/file")
@Tag(name = "附件")
@Log4j2
public class FileController {

    @Autowired
    private FileService fileService;

    @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @ResponseBody
    @Operation(summary = "附件上传")
    public FileUploadVO upload(@RequestPart(value = "file", required = false) MultipartFile file, FileUploadDTO dto) {
        return fileService.upload(file, dto);
    }

    @GetMapping("download/{id}")
    @Operation(summary = "附件下载")
    public void download(@PathVariable("id") String id) {
        FileDownloadVO vo = fileService.download(id);
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        try {
            if (servletRequestAttributes != null) {
                HttpServletResponse response = servletRequestAttributes.getResponse();
                if (response != null) {
                    OutputStream out = response.getOutputStream();
                    response.reset();
                    response.setContentType("application/octet-stream; charset=utf-8");
                    response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(vo.getName() + "." + vo.getExt(), "UTF-8"));
                    // byte b[]
                    out.write(vo.getBytes());
                    out.flush();
                }
            }
            throw new IllegalArgumentException("response not found!");
        } catch (Exception e) {
            log.error(e);
        }
    }
}
